package cn.iborder.utils;

import java.io.IOException;
import java.io.InputStream;

import javax.websocket.Session;

import com.jfinal.log.Log;

import cn.iborder.controller.WebSocketController;
import cn.iborder.core.ResPool;

public class ShellOutput extends Thread {
	private static Log log = TrcLog.getLogFile();
	private final Session session;
	private final InputStream out;

	public ShellOutput(Session session, InputStream out) {
		super();
		this.session = session;
		this.out = out;
	}

	@Override
	public synchronized void start() {
		// TODO Auto-generated method stub
		super.start();
	}

	@Override
	public void run() {
		super.run();

		log.info("[ShellOutput]inShellDataSize:"+ResPool.getConfigPool().getInt("inShellDataSize"));
		//byte[] buff = new byte[PropKit.getInt("inShellDataSize")];
		byte[] buff = new byte[ResPool.getConfigPool().getInt("inShellDataSize")];
		StringBuilder sb = new StringBuilder();
		try {
			while (session != null && session.isOpen()) {
				sb.setLength(0);
				int len = out.read(buff);
				if (len == -1)
					return;
				for (int i = 0; i < len; i++) {
					char c = (char) (buff[i] & 0xff);
					sb.append(c);
				}
				
				WebSocketController.sendBinaryMsg(session, sb.toString());
				//限制输出间隔时间
				try {
					//Thread.sleep(PropKit.getInt("inShellInterval"));
					Thread.sleep(ResPool.getConfigPool().getInt("inShellInterval"));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			log.info("[ShellOutput]读取shell响应通道异常");
			throw new RuntimeException(e);
		}
	}

}
